/**
 * Created by user on 2015/12/3.
 */

angular.module('mis.themeManager.controllers', [])
    .controller('themeCtrl', ['$scope','$http', '$location', function ($scope, $http, $location) {


        $scope.currentPage = 1;
        $scope.pageSize = 15;

        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/theme/themeList/:page/:size',
            ajax: $http,
            success:function(data){
                $scope.resultList = GetCategoryName(data.data.list,'image');
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);

            },
            error: function(err){
                //$scope.communityList = null;
            },
            params: {}
        });

        //全选列表
        $scope.allSelected = function () {
            $scope.pagination.allSelected();
        };

        $scope.selectFile = function (files,model,type) {
            if (model == 'add') {
                if(type =='share'){
                    document.getElementById("image_share").innerHTML = '';
                }else{
                    document.getElementById("image_result").innerHTML = '';
                }
            }else{
                if(type =='share'){
                    document.getElementById("image_share_edit").innerHTML = '';
                }else{
                    document.getElementById("image_result_edit").innerHTML = '';
                }
            }
            showImages(model,type);
        };

        var reader = null;
        var readerShare = null;

        if (FileReader) {
            reader = new FileReader();
            readerShare = new FileReader();
        } else {
            alert("浏览器暂时不支持FileReader");
        }
        var imageEle,imageEleShare;
        var fileList = {}, length = 0, length1 = 0;
        var fileListShare = {};
        var showImages = function (model,type) {

            if(model =='add'){
                if(type =='share'){
                    imageEleShare  = document.getElementById("images_upload_share");
                }else {
                    imageEle = document.getElementById("images_upload");
                }
            }else{
                if(type =='share'){
                    imageEleShare  = document.getElementById("images_upload_share_edit");
                }else {
                    imageEle = document.getElementById("images_upload_edit");
                };
            }

            if(type == 'share'){
                //获取上传的分享图片
                fileListShare = imageEleShare.files;
            }else{
                //获取上传的多个文件
                fileList = imageEle.files;
                length = fileList.length;
                length1 = fileList.length;
            }

            //获取文件信息
            readURL(model,type);
        };

        var readURL = function (model, type) {

            if(type =='share'){

                readerShare.readAsDataURL(fileListShare[0]);
                readerShare.onload = function () {
                    var img = document.createElement("img");
                    img.src = readerShare.result;
                    img.width = 200;
                    if (model == 'add') {
                        document.getElementById("image_share").appendChild(img);
                    } else {
                        document.getElementById("image_share_edit").appendChild(img);
                    }
                };

            }else {

                reader.readAsDataURL(fileList[length1 - length]);
                reader.onload = function () {
                    var img = document.createElement("img");
                    img.src = reader.result;
                    img.width = 200;
                    if (model == 'add') {
                        document.getElementById("image_result").appendChild(img);
                    } else {
                        document.getElementById("image_result_edit").appendChild(img);
                    }
                    length--;
                    if (length == 0)return;
                    readURL(model, type);
                };

            }

        };


        $scope.addTheme = function(addData, temp){

            var target = temp.target;

            var opt = {
                title : addData.title
                ,subTitle : addData.subTitle
                ,desc : addData.desc
            };

            if(addData.shareDesc) {
                opt.shareDesc = addData.shareDesc;
            }else{
                opt.shareDesc = addData.desc;
            };

            var fd = new FormData();
            var index = 0;
            if (fileListShare != null) {
                if(fileListShare.length>0) {
                    fd.append('image1', fileListShare[0]);
                    index =1;
                };
            };
            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    index = index + 1;
                    fd.append('image' + index, fileList[i]);
                }
            };

            if(fileList.length>0 || fileListShare.length>0){

                if(fileList.length>1){
                    alert('上传图片不能超过1张!');
                    return;
                };

                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {

                    var uploadImages = [];
                    for(var i=0;i<images.data.length;i++) {
                        if (images.data[i] != null) {
                            //如果存在shareImage取第一张图片
                            if(fileListShare.length>0 && i==0){
                                opt.shareImage = images.data[i];
                            }else{
                                uploadImages.push({imageURL:images.data[i]})
                            };
                        };

                    };
                    opt.images = uploadImages;

                    if(!opt.shareImage)opt.shareImage =images.data[0];


                    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/theme/themeAdd', opt, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.addData = {};
                        $scope.pagination.selectPage(1);//插入成功显示第一页
                        $('#doc-modal-add').modal("close");
                        alert("添加话题成功");

                    }).error(function (err) {
                        alert(err);
                    });

                });

            }else{

                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/theme/themeAdd', opt, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.addData = {};
                    $scope.pagination.selectPage(1);//插入成功显示第一页
                    $('#doc-modal-add').modal("close");
                    alert("添加话题成功");

                }).error(function (err) {
                    alert(err);
                });
            };

        }


        //编辑
        $scope.themeEdit = function(them){

            fileList = {};
            fileListShare = {};
            $scope.updataData = them;
            $('#doc-modal-edit').modal({target: '#doc-modal-edit', width: 800, height: 600});

        };

        $scope.updateTheme = function(updataData,temp){
            var target = temp.target;

            var uData = {themeID:"",theme:{}};
            if(updataData.objId)uData.themeID = updataData.objId;

            if(updataData.title != null)uData.theme.title = updataData.title;
            if(updataData.subTitle != null)uData.theme.subTitle = updataData.subTitle;
            if(updataData.desc != null)uData.theme.desc = updataData.desc;
            if(updataData.shareKey != null)uData.theme.shareKey = updataData.shareKey;

            if(updataData.shareDesc){
                uData.theme.shareDesc = updataData.shareDesc;
            }else{
                uData.theme.shareDesc = updataData.desc;
            };

            var fd = new FormData();
            var index = 0;
            if (fileListShare != null) {
                if(fileListShare.length>0) {
                    fd.append('image1', fileListShare[0]);
                    index =1;
                };
            };
            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    index = index + 1;
                    fd.append('image' + index, fileList[i]);
                }
            };

            if(fileList.length>0  || fileListShare.length>0){

                if(fileList.length>1){
                    alert('上传图片不能超过1张!');
                    return;
                };

                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {
                    //uData.theme.shareImage = images.data[0];
                    //uData.theme.imageURL = images.data[1];

                    var uploadImages = [];
                    for(var i=0;i<images.data.length;i++) {
                        if (images.data[i] != null) {
                            //如果存在shareImage取第一张图片
                            if(fileListShare.length>0 && i==0){
                                uData.theme.shareImage = images.data[i];
                            }else{
                                uploadImages.push({imageURL:images.data[i]})
                            };
                        };
                    };
                    if (fileList.length>0 && uploadImages.length>0) {
                        uData.theme.images = uploadImages;
                    };
                    if(!uData.theme.shareImage)uData.theme.shareImage =images.data[0];
                    console.debug(uData);
                    var params = {
                        url: 'http://' + backOfficeHost + '/rest/v1.0/mis/theme/themeEdit',
                        updateData: uData,
                        success: function (data) {
                            //var pageNumber = $(".am-active").text();//当前页码
                            $('#doc-modal-edit').modal("close");
                            $('#image_result_edit').empty();
                            $('#image_share_edit').empty();
                            $scope.updataData = null;
                            //$scope.pagination.selectPage(pageNumber);
                            if (data.result.status == 1) {
                                $scope.search(true);
                                alert("修改成功！");
                            } else {
                                alert("修改失败！");
                            }
                        },
                        error: function () {
                            $('#doc-modal-edit').modal("close");
                            $('#image_result_edit').empty();
                            $('#image_share_edit').empty();
                            $scope.updataData = null;
                            alert("修改失败！");
                        }
                    };
                    $scope.pagination.listUpdate(params);

                });


            }else {

                var params = {
                    url: 'http://' + backOfficeHost + '/rest/v1.0/mis/theme/themeEdit',
                    updateData: uData,
                    success: function(data){
                        //var pageNumber = $(".am-active").text();//当前页码
                        $('#doc-modal-edit').modal("close");
                        $('#image_result_edit').empty();
                        $('#image_share_edit').empty();
                        $scope.updataData = null;
                        if(data.result.status == 1){
                            $scope.search(true);
                            alert("修改成功！");
                        }else{
                            alert("修改失败！");
                        }
                    },
                    error: function(){
                        $('#doc-modal-edit').modal("close");
                        $('#image_result_edit').empty();
                        $('#image_share_edit').empty();
                        $scope.updataData = null;
                        alert("修改失败！");
                    }
                };
                $scope.pagination.listUpdate(params);

            };




        };

        $scope.search = function(current) {

            if (current) {
                $scope.currentPage = $scope.pagination.currentPage;
            }else {
                $scope.pagination.currentPage = 1;
                $scope.currentPage = 1;
            }

            var body = {};
            if ($scope.themeTitle) body.title = $scope.themeTitle;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/theme/themeList/' + $scope.currentPage + '/' + $scope.pageSize, body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                $scope.resultList = GetCategoryName(data.data.list,'image');
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;

                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = body;

            }).error(function (err) {
                $scope.topicList = null;
            });
        };



    }])


